package com.ubix.kiosoft2.services;

import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.ubix.kiosoft2.EventReader;
import com.ubix.kiosoft2.utils.Constants;
import com.ubix.kiosoft2.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.UUID;

import static com.ubix.kiosoft2.EventReader.EVENT_TYPE_START_SCAN_ERROR;
import static com.ubix.kiosoft2.EventReader.EVENT_TYPE_STOP_SCAN_ERROR;

/**
 * @Created by Chris on 8/4/2016.
 */
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mLeScanner;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private int mConnectionState = STATE_DISCONNECTED;

    private BluetoothGattService gattService;
    private BluetoothGattCharacteristic characteristic;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public static final int BYTE_ARRAY_SIZE = 20;

    private byte[] packet = null;

    public final static String ACTION_GATT_CONNECTED =
            "com.ubix.kiosoft.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.ubix.kiosoft.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_UNEXPECTED_DISCONNECT =
            "com.ubix.kiosoft.ACTION_GATT_UNEXPECTED_DISCONNECT";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.ubix.kiosoft.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_GATT_SERVICES_ERROR =
            "com.ubix.kiosoft.ACTION_GATT_SERVICES_ERROR";
    public final static String ACTION_GATT_CHARACTERISTIC_ERROR =
            "com.ubix.kiosoft.ACTION_GATT_CHARACTERISTIC_ERROR";
    public final static String ACTION_DATA_AVAILABLE =
            "com.ubix.kiosoft.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.ubix.kiosoft.EXTRA_DATA";
    public final static String ACTION_DATA_RETURNED =
            "com.ubix.kiosoft.ACTION_DATA_RETURNED";

    boolean isConnected = false;
    boolean isExpectedDisconnect = false;

    /**
     * 1:ME51<p>
     * 2:STM32 reader
     */
    int machineType = 0;

    // Implements callback methods for GATT events that the app cares about.  For example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            Log.i("robin", "onConnectionStateChange: status==" + status + "  newState==" + newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                try {
                    Thread.sleep(600);
                    Log.i(TAG, "Attempting to start service discovery:" +
                            mBluetoothGatt.discoverServices());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                if (isExpectedDisconnect) {
                    intentAction = ACTION_GATT_DISCONNECTED;
                    Log.i(TAG, "Disconnected intentionally from GATT server.");
                } else {
                    intentAction = ACTION_GATT_UNEXPECTED_DISCONNECT;
                    Log.i(TAG, "Disconnected unintentionally from GATT server.");
                }
                isExpectedDisconnect = false;
                mConnectionState = STATE_DISCONNECTED;
                isConnected = false;
//                if (status == 133) {
//                    mBluetoothAdapter.disable();
//                    mBluetoothAdapter.enable();
//                }
                close();
                broadcastUpdate(intentAction);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.i(TAG, "onServicesDiscovered: status==" + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                gattService = gatt.getService(UUID.fromString(Constants.ME51_SERVICE_UUID));
                machineType = 1;
                Log.i(TAG, "onServicesDiscovered: 11111111" + gattService);
                if (gattService == null) {
                    machineType = 2;
                    gattService = gatt.getService(UUID.fromString(Constants.SERVICE_UUID));
                }

                if (gattService == null) broadcastUpdate(ACTION_GATT_SERVICES_ERROR);
                else {
                    //设置写的UUID
                    if (machineType == 1) {
                        characteristic = gattService.getCharacteristic(UUID.fromString(Constants.ME51_CHAR_WRITE_UUID));
                    } else if (machineType == 2) {
                        characteristic = gattService.getCharacteristic(UUID.fromString(Constants.CHARACTERISTIC_UUID));
                    }

                    if (characteristic == null) {
                        broadcastUpdate(ACTION_GATT_CHARACTERISTIC_ERROR);
                    } else {
                        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                    }
                }

            } else if (status == 129) {//in nexus4 android 4.3 sometimes will 129
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "              Connection Failed\nRestart your Bluetooth and try again", Toast.LENGTH_LONG).show();
                    }
                });
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
                String v = new String(characteristic.getValue());
                Utils.printByteAsHex(characteristic.getValue(), "READ");
            }
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            Log.d("RW", "DONE");
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            broadcastUpdate(ACTION_DATA_RETURNED, characteristic);
        }
    };

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);

        // This is special handling for the Heart Rate Measurement profile.  Data parsing is
        // carried out as per profile specifications:
        // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml

        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, stringBuilder.toString());
        }
        sendBroadcast(intent);
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize(Activity activity) {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        if (mBluetoothAdapter.isEnabled()) leScanInit();
        else turnOnBluetooth(activity, Constants.REQUEST_ENABLE_BT_SERVICE);

        return true;
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     * @return Return true if the connection is initiated successfully. The connection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public boolean connect(final String address) {
        if (!isConnected) {
            Log.w("IS NOT CONNECTED", "CONNETCING");
            if (mBluetoothAdapter == null || address == null) {
                Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
                return false;
            }

            // Previously connected device.  Try to reconnect.
            if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                    && mBluetoothGatt != null) {
                Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
                if (mBluetoothGatt.connect()) {
                    mConnectionState = STATE_CONNECTING;
                    isConnected = true;
                    return true;
                } else {
                    return false;
                }
            }

            final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            if (device == null) {
                Log.w(TAG, "Device not found.  Unable to connect.");
                return false;
            }
            // We want to directly connect to the device, so we are setting the autoConnect
            // parameter to false.
            mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

            Log.d(TAG, "Trying to create a new connection.");
            mBluetoothDeviceAddress = address;
            isConnected = true;
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            Log.w("IS CONNECTED", "NOT DOING ANYTHING");
            return false;
        }
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The disconnection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        isExpectedDisconnect = true;
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * Write characteristic
     *
     * @param characteristic
     */
    public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.writeCharacteristic(characteristic);
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        //设置读数据的UUID
        if (machineType == 1) {
            characteristic = gattService.getCharacteristic(UUID.fromString(Constants.ME51_CHAR_NOTIFY_UUID));
        } else if (machineType == 2) {
            characteristic = gattService.getCharacteristic(UUID.fromString(Constants.CHARACTERISTIC_UUID));
        }

        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    }

    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) return null;

        return mBluetoothGatt.getServices();
    }

    /**
     * Returns bluetooth gatt object;
     *
     * @return BluetoothGatt
     */
    public BluetoothGatt getGatt() {
        if (mBluetoothGatt == null) return null;
        return mBluetoothGatt;
    }

    public boolean turnOnBluetooth(Activity activity, int result) {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, result);
            return false;
        } else {
            leScanInit();
            return true;
        }
    }

    public void startScan(ScanCallback ScanCallback, BluetoothAdapter.LeScanCallback LeScanCallback) {
        Log.w("Start Scan", "START");
        if (Build.VERSION.SDK_INT > 21) {
            if (mLeScanner != null && ScanCallback != null && mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
                ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
                mLeScanner.startScan(null, scanSettings, ScanCallback);
//                mLeScanner.startScan(ScanCallback);
            } else {
                Log.e(TAG, "startScan: 出错了111");
                EventBus.getDefault().post(new EventReader(EVENT_TYPE_START_SCAN_ERROR));
                EventBus.getDefault().post(new EventReader("\n\n！！BluetoothLeService : startScan: 出错了！！\n"));
            }
        } else {
            mBluetoothAdapter.startLeScan(LeScanCallback);
        }
    }

    public void stopScan(ScanCallback ScanCallback, BluetoothAdapter.LeScanCallback LeScanCallback) {
        if (Build.VERSION.SDK_INT > 21) {
            if (mLeScanner != null && ScanCallback != null && mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
                mLeScanner.stopScan(ScanCallback);
            } else {
                Log.e(TAG, "stopScan: 出错了222");
                EventBus.getDefault().post(new EventReader(EVENT_TYPE_STOP_SCAN_ERROR));
                EventBus.getDefault().post(new EventReader("\n\n！！BluetoothLeService : stopScan: 出错了！！\n"));
            }
        } else {
            mBluetoothAdapter.stopLeScan(LeScanCallback);
        }
    }

    public boolean leScanInit() {
        if (Build.VERSION.SDK_INT > 21) {
            mLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
            if (mLeScanner == null) {
                Log.e(TAG, "Unable to initialize BluetoothLeScanner.");
                return false;
            } else return true;
        } else return true;
    }

    // todo jog
//    public boolean sendDatabyString(String data, @Nullable String cmd) {
//        byte[] dataByte = Utils.hexStringToByteArray(data);
//        return sendData(dataByte, cmd);
//    }

    /**
     * todo jog
     */
    public boolean sendData(@Nullable byte[] data) {
        if (characteristic != null && mBluetoothGatt != null) {
            setCharacteristicNotification(characteristic, true);

            final byte[][] packet = Utils.devideBytes(data, BYTE_ARRAY_SIZE); // todo jog: 20bytes一小包
            for (final byte[] pa : packet) {
                characteristic.setValue(pa);
                write(mBluetoothGatt, characteristic);
            }
            return true;
        } else return false;
    }

    /**
     * todo jog: test for ME51, 不分包，直接全部发送
     * ## 不可用！
     */
//    public boolean sendData(@Nullable byte[] data) {
//        if (characteristic != null && mBluetoothGatt != null) {
//            setCharacteristicNotification(characteristic, true);
//            characteristic.setValue(data);
//            write(mBluetoothGatt, characteristic);
//            return true;
//        } else return false;
//    }
    public boolean sendData(byte[][] packet) {
        if (characteristic != null && mBluetoothGatt != null) {
            setCharacteristicNotification(characteristic, true);
            for (final byte[] pa : packet) {
                Utils.printByteAsHex(pa, "Data Sent");
                characteristic.setValue(pa);
                write(mBluetoothGatt, characteristic);

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return true;
        } else return false;
    }

    public void write(BluetoothGatt mBluetoothGatt, BluetoothGattCharacteristic characteristic) {
        boolean pstatus = mBluetoothGatt.writeCharacteristic(characteristic);
        Log.e("imtest", "pstatus:" + pstatus);
        try {
            if (pstatus) {
                Thread.sleep(50);
            } else {

                Thread.sleep(100);

                write(mBluetoothGatt, characteristic);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Log.e("imtest", e.getMessage());
        }
    }

    public static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_RETURNED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CHARACTERISTIC_ERROR);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_ERROR);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_UNEXPECTED_DISCONNECT);

        return intentFilter;
    }
}
